<template>
	<view class="flex" style="flex-wrap: wrap;" :style="hidden?'width: 0;height:0;overflow: hidden;':''">

		<!-- 图片列表 -->
		<view :style="{width,height,marginTop,marginRight}" class="upload-img pr" v-for="(item,index) in image_list"
			:key="index">
			<!-- <image @tap="preview(index)" :src="item.path || item.src" mode="aspectFill"></image> -->
			<view v-if="item.src.endsWith('.mp4')" style="width: 145rpx;height: 145rpx;">
				<video ref="videoPlayer" id="videoPlayer" style="width: 100%; height: 100%;" :src="item.src" controls />
			</view>
			<image v-else mode="aspectFill" :src="item.path || item.src"></image>

			<!-- 删除按钮 -->
			<view class="upload-del" style="">
				<view @tap.stop="del_img(index)" class="iconfont icon-lajitong color-ffffff" style="font-size: 38rpx;">
				</view>

			</view>
			<!-- 删除按钮 -->

			<!-- 上传遮罩 -->
			<view class="upload-box" v-if="!item.src">
				<view>上传中...</view>
			</view>
			<!-- 上传遮罩 -->

		</view>
		<!-- 图片列表 -->

		<!-- 上传图片按钮 -->
		<view v-if="length > image_list.length" :style="{width,height,marginTop,marginRight}" class="upload-btn"
			hover-class="click" @tap="choose_image()">
			<view class="iconfont icon-tupian color-999999 fs-34"></view>
			<view v-if="desc" class="fs-22 color-999999">{{desc}}</view>
		</view>
		<!-- 上传图片按钮 -->
		<powers1 ref="powers1" type="top" @changeAuth="changeAuth" :permissionID="permissionID"></powers1>

		<powers ref="powers"></powers>


	</view>
</template>

<script>
	import powers1 from '@/components/powers/powers1.vue'
	export default {
		name: 'upload',
		components: {
			powers1
		},
		props: {
			width: {
				type: String,
				default: '145rpx',
			},
			height: {
				type: String,
				default: '145rpx',
			},
			//整个容器宽度
			contentWidth: {
				type: String,
				default: '100%',
			},
			marginRight: {
				type: String,
				default: '20rpx',
			},
			marginTop: {
				type: String,
				default: '20rpx',
			},
			length: {
				type: Number,
				default: 1,
			},
			hidden: {
				type: Boolean,
				default: false,
			},
			//压缩后图片宽度
			imageWidth: {
				type: Number,
				default: 0,
			},
			desc: {
				type: String,
				default: '',
			}
		},
		data() {
			return {
				permissionID: '',
				videoUploaded: false,
				typevideo: '',
				image_list: [

				],

			}
		},
		onLoad() {
			console.log('this.image_list', this.image_list)
		},
		methods: {
			// 上传文件（图片或视频）
			upload_file(filePath, id, type) {
				if (type === 'image') {
					// 上传图片的处理逻辑
					if (this.imageWidth === 0) {
						this.upload_image(filePath, id);
					} else {
						// #ifdef H5
						this.upload_image(filePath, id);
						// #endif
						// #ifndef H5
						uni.compressImage({
							src: filePath,
							width: this.imageWidth,
							success: img => {
								this.upload_image(img.tempFilePath, id);
							},
							fail: err => {
								console.log('err', err);
							}
						});
						// #endif
					}
				} else if (type === 'video') {
					// 上传视频的处理逻辑
					if (!this.videoUploaded) {
						console.log(filePath, 'filePath')
						this.upload_image(filePath, id);
						this.videoUploaded = true; // 上传视频后设置为已上传
						this.typevideo = 'typevideo'; // 上传视频后设置为已上传
					} else {
						return this.showToast('只能上传一个视频！')
					}
					// this.upload_image(filePath, id);
				}
			},
			choose_image_from_album(sourceType) {
				uni.chooseImage({
					sourceType: sourceType,
					count: this.length - this.image_list.length,
					success: res => {
						let {
							tempFilePaths = []
						} = res;
						tempFilePaths.forEach(val => {
							let id = new Date().getTime().toString();
							this.image_list.push({
								path: val,
								src: '',
								id,
								type: 'image', // 标识是图片
							});
							this.upload_file(val, id, 'image'); // 上传图片
						});
					}
				});
			},

			choose_video_from_album() {
				uni.chooseVideo({
					sourceType: ['album', 'camera'], // 支持选择相册和拍摄
					count: 1,
					success: res => {
						console.log('上传视频', res)
						let {
							thumbTempFilePath,
							tempFilePath,
							duration,
							size,
							height,
							width
						} = res;
						console.log('r33es', res)
						let id = new Date().getTime().toString();
						this.image_list.push({
							path: tempFilePath,
							imgUrl: thumbTempFilePath, //封面
							src: '',
							id,
							type: 'video', // 标识是视频
							duration, // 视频时长
							size, // 视频大小
							height, // 视频高度
							width, // 视频宽度
						});
						this.upload_file(tempFilePath, id, 'video'); // 上传视频
					}
				});
			},


			// 现在的

			//用户授权权限后的回调
			changeAuth(sourceType = ['album', 'camera']) {
				uni.showActionSheet({
					itemList: ['选择图片', '选择视频'], // 可以选择图片或视频
					success: res => {

						// console.log('this.image_list[0].type',this.image_list[0].type)
						// if(this.image_list[0].type == "image"){

						// 	this.choose_image_from_album(sourceType);


						// }

						if (res.tapIndex === 0) { // 如果选择的是图片
							this.choose_image_from_album(sourceType);
						} else if (res.tapIndex === 1) { // 如果选择的是视频
							this.choose_video_from_album();
						}
						// if (res.tapIndex === 0) { // 如果选择的是图片
						// 	this.choose_image_from_album(sourceType);
						// } else if (res.tapIndex === 1) { // 如果选择的是视频
						// 	this.choose_video_from_album();
						// }
					}
				});
				//这里是权限通过后执行自己的代码逻辑
				console.log('权限已授权，可执行自己的代码逻辑了');
			},

			choose_image(sourceType = ['album', 'camera']) {
				if (this.image_list.length == 0) {
					this.videoUploaded = false;
				}

				if (this.length <= this.image_list.length)
					return;

				// #ifdef H5
				sourceType = ['album'];
				// #endif

				if (this.videoUploaded) {
					return this.showToast('只能上传一个视频！')
				}
				if (uni.getSystemInfoSync().platform == "ios") {
					this.$refs.powers.open({
						powersType: "POWERS_IMAGE",
						success: () => {
							////////////

							uni.showActionSheet({
								itemList: ["选择图片", "选择视频"], // 可以选择图片或视频
								success: (res) => {
									if (res.tapIndex === 0) {
										// 如果选择的是图片
										this.choose_image_from_album(sourceType);
									} else if (res.tapIndex === 1) {
										// 如果选择的是视频
										this.choose_video_from_album();
									}
								},
							});
							////////////
						},
					});
				} else {
					this.permissionID = "CAMERA";
					setTimeout(() => {
						this.$refs['powers1'].open();
					}, 500)
					uni.chooseImage({
						sourceType: ['album'],
						count: this.length - this.image_list.length,
						success: res => {
							// console.log(res);
							let {
								tempFilePaths = []
							} = res
							tempFilePaths.forEach(val => {
								let id = new Date().getTime().toString();
								this.image_list.push({
									path: val,
									src: '',
									id,
								});
								if (this.imageWidth == 0) {
									this.upload_image(val, id);
								} else {
									// #ifdef H5
									this.upload_image(val, id);
									// #endif
									// #ifndef H5
									uni.compressImage({
										src: val,
										width: this.imageWidth,
										success: img => {
											this.upload_image(img
												.tempFilePath, id);
										},
										fail: err => {
											console.log('err', err);
										}
									});
									// #endif
								}
							})


						}
					})
				}

			},
			upload_image(url, id) {
				let appUrl = this.ROOT + '/upload/image';
				uni.uploadFile({
					url: appUrl,
					filePath: url,
					data: {
						img: 'file',
						name: 'file'
					},
					name: 'file',
					success: img_data => {
						// console.log('img_Data', img_data);

						if (img_data.statusCode == 200 && img_data.errMsg == 'uploadFile:ok') {
							let data = JSON.parse(img_data.data);
							if (data.status == 200) {
								this.image_list.forEach((val, index) => {
									console.log('val', val)
									if (val.id == id) {
										val.src = data.data;
										// val.id = data.data.image_id;

										// console.log('上传成功', id, index, val)
										this.$emit('change', this.image_list);
									}
								})
							} else {
								this.image_list.forEach((val, index) => {
									if (val.id == id) {
										val.id = '';
									}
								});
								this.$emit('change', this.image_list);
								this.showToast('您上传的图片含敏感内容，上传失败');
							}

						}
					}
				})

			},
			preview(index) {
				uni.previewImage({
					current: index,
					urls: this.image_list.map(val => val.path || val.src)
				})
			},
			del_img(index) {
				this.image_list.splice(index, 1);
				this.$emit('change', this.image_list);
			}
		}
	}
</script>

<style lang="scss">
	.upload-btn {
		background-color: #F5F6F7;
		border-radius: 8rpx;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		// border: 2rpx dashed #cdc9c9;
	}

	.upload-img {
		background-color: #FFFFFF;
		border-radius: 8rpx;
		overflow: hidden;

		image {
			width: 100%;
			height: 100%;
		}
	}

	.upload-del {
		position: absolute;
		right: 0rpx;
		top: 0rpx;
		z-index: 5;
		width: 48rpx;
		height: 48rpx;
		background-color: rgba(0, 0, 0, 0.7);
		display: flex;
		justify-content: center;
		align-items: center;
		border-radius: 0 0 0 10rpx;
	}

	.upload-box {
		position: absolute;
		width: 100%;
		height: 100%;
		top: 0;
		left: 0;
		background-color: rgba(0, 0, 0, 0.5);
		display: flex;
		justify-content: center;
		align-items: center;
		color: #FFFFFF;
		font-size: 24rpx;
		z-index: 4;
	}
</style>